package com.mayisoftware.mayioa.business.personal.impl.controller;


import com.mayisoftware.mayioa.business.flow.api.domain.BaseFlowInfo;
import com.mayisoftware.mayioa.business.flow.api.service.IFlowBaseService;
import com.mayisoftware.mayioa.business.personal.api.domain.PersonToDo;
import com.mayisoftware.mayioa.business.personal.api.domain.PersonalSign;
import com.mayisoftware.mayioa.business.personal.api.service.IPersonalSignService;
import com.mayisoftware.mayioa.common.api.constant.Constants;
import com.mayisoftware.mayioa.common.impl.utils.bean.ReflectionUtil;
import com.mayisoftware.mayioa.platform.api.domain.SysRole;
import com.mayisoftware.mayioa.platform.api.domain.SysUser;
import com.mayisoftware.mayioa.platform.api.service.ISysUserService;
import com.mayisoftware.mayioa.platform.impl.util.ShiroUtils;
import com.mayisoftware.mayioa.platform.impl.web.base.BaseController;
import com.mayisoftware.mayioa.platform.impl.web.page.TableDataInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 用户报名控制器
 */
@Controller
@RequestMapping("/personal/todo")
public class PersonalTodoController extends BaseController{
    /**
     * URL前缀
     */
    private String prefix = "personal/todo";
    /**
     * 用户报名相关服务
     */
    @Autowired
    private IPersonalSignService personalSignService;

    @Autowired
    private TaskService taskService;

    /**
     * 用户查询服务
     */
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 流程处理服务
     */
    @Autowired
    private IFlowBaseService flowBaseService;

    @RequiresPermissions("personal:todo:view")
    @GetMapping()
    public String view()
    {
        return prefix + "/todo";
    }

    @RequiresPermissions("personal:todo:list")
    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo list(PersonToDo personToDo)
    {
//        startPage();

        List<PersonToDo> result = new ArrayList<>();


        SysUser user= ShiroUtils.getSysUser();

        if (user == null){
            return  getDataTable(result);
        }

        List<SysRole> roles =  user.getRoles();

        List<String> groupInfo = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roles)){
            for (SysRole role:roles){
                groupInfo.add(role.getRoleName());
            }
        }

        List<Task> tasks= flowBaseService.queryTasks(user.getUserId().toString(),user.getUserId().toString(),groupInfo);

        if (!CollectionUtils.isEmpty(tasks)){
            for (Task task : tasks){
                PersonToDo todo = new PersonToDo();
                String processId = task.getProcessInstanceId();

                if (StringUtils.isEmpty(processId)){
                    continue;
                }
                todo.setProcessId(processId);
                PersonalSign tmpApply =  new PersonalSign();
                tmpApply.setProcessId(processId);
                List<PersonalSign> signs = personalSignService.queryApplyInfo(tmpApply);

                if (CollectionUtils.isEmpty(signs)){
                    continue;
                }

                //查询流程基本信息
                PersonalSign sign = signs.get(0);

                todo.setApplyFile(sign.getApplyFile());
                todo.setPlanName(sign.getPlanName());
                todo.setUserId(sign.getPerSignUserId().toString());
                todo.setPlanId(sign.getPerSignPlanId().toString());

                SysUser tmpUser= sysUserService.selectUserById(sign.getPerSignUserId().longValue());
                todo.setCurrentStatus("进行中");
                todo.setRecordId(sign.getPerSignRecordId().toString());
                todo.setUserName(tmpUser.getUserName());
                todo.setTaskId(task.getId());
                todo.setTaskName(task.getName());
                if (task.getCreateTime() != null){
                    todo.setTaskStartTime(Constants.YMD_HMS_FMT.format( task.getCreateTime()));
                }

                if(flowBaseService.isFinished(todo.getProcessId())){
                    todo.setCurrentStatus("已结束");
                }

                HistoricProcessInstance pi = flowBaseService.queryProcessInfo(todo.getProcessId());

                todo.setProcessName(pi.getProcessDefinitionName());
                if (null != pi.getStartTime()){
                    todo.setFlowStartTime(Constants.YMD_HMS_FMT.format(pi.getStartTime()));
                }

                if (null != pi.getEndTime()){
                    todo.setFlowEndTime(Constants.YMD_HMS_FMT.format(pi.getEndTime()));
                }

                if (!StringUtils.isEmpty(personToDo.getProcessName()) && !pi.getProcessDefinitionName().contains(personToDo.getProcessName())){
                    continue;
                }
                else {
                    result.add(todo);
                }
            }
        }

        return getDataTable(result);
    }

    /**
     * 审批历史
     */
    @GetMapping("/check")
    public String check(ModelMap mmap)
    {
        return prefix + "/check";
    }
}
